package com.oneplus.network.core;


import com.oneplus.network.ehcacheManager.InitializationManager;
import com.oneplus.repositorys.BlockRepository;
import com.oneplus.repositorys.TokenRepository;
import com.oneplus.repositorys.TransactionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;



@Component
public class ResetData {
    @Autowired
    private BlockRepository blockRepository;
    @Autowired
    private TokenRepository tokenRepository;
    @Autowired
    private TransactionRepository transactionRepository;
    @Autowired
    private GenesisBlock genesisBlock;
    @Autowired
    private InitializationManager initializationManager;

    @Transactional
    public void resetAll() {
        tokenRepository.truncate ( );
        blockRepository.truncateRelation ( );
        transactionRepository.truncate ( );
        blockRepository.truncate ( );
        genesisBlock.init ( );
    }

    @Transactional
    public void resetAssets() {

    }

    @Transactional
    public void backBlock(int blockHeight) {
        if (blockHeight > blockRepository.count())return;
        long backBlockHeight = initializationManager.getBlockHeight ( ) - blockHeight;
        List<String> signatureList = blockRepository.getSignatureByBlockHeight ( backBlockHeight );
        blockRepository.deleteRelation ( signatureList );
        blockRepository.deleteBlock ( backBlockHeight );
        List<String> tokenNameList = transactionRepository.getTokenNameByQuerey ( backBlockHeight );
        transactionRepository.deleteByBlockHeight ( backBlockHeight );
        if (tokenNameList.size()>0) {
            tokenRepository.deleteByTokenName(tokenNameList);
        }
        initializationManager.setLastBlock ( blockRepository.findBlockByBlockId ( backBlockHeight ) );
    }

    @Transactional
    public void backBlockByblockHeight(long blockHeight) {
        List<String> signatureList = blockRepository.getSignatureByBlockHeight ( blockHeight );
        blockRepository.deleteRelation ( signatureList );
        blockRepository.deleteBlock ( blockHeight );
        List<String> tokenNameList = transactionRepository.getTokenNameByQuerey ( blockHeight );
        transactionRepository.deleteByBlockHeight ( blockHeight );
        if (tokenNameList.size()>0){
            tokenRepository.deleteByTokenName ( tokenNameList );
        }
        initializationManager.setLastBlock ( blockRepository.findBlockByBlockId ( blockHeight ) );
    }
}
